package com.ethink.platform.manager;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.ethink.framework.common.exception.BusinessException;
import com.ethink.order.api.constant.OrderRespCode;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author default
 * @version 1.0.0
 * @ClassName ExcelImportManager.java
 * @Description
 * @createTime 2022年11月09日 16:30:00
 */
@Component
public class ExcelImportManager {

    private static final Integer SIZE = 5000;


    /**
     *
     * @param file
     * @param t
     * @param size  限制导入数量
     * @param <T>
     * @return
     */
    public <T> List<T> transferClass(MultipartFile file, Class<T> t, Integer size) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            List<Map<String, String>> excelField = getExcelField(t);
            for (Map<String, String> map : excelField) {
                reader.addHeaderAlias(map.get("header"),map.get("alias"));
            }
            List<T> data = reader.readAll(t);
            //校验数量
            if (data.size() > size) {
                throw new BusinessException(OrderRespCode.EXCEL_DATA_SIZE);
            }
            return data;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public <T> List<T> transferClass(MultipartFile file, Class<T> t) {
        return transferClass(file,t,SIZE);
    }

    public <T> List<Map<String,String>> getExcelField(Class<T> t){
        List<Map<String,String>> list = new ArrayList<>();
        Field[] declaredFields = t.getDeclaredFields();
        if (ArrayUtil.isEmpty(declaredFields)){
            return list;
        }
        for (Field declaredField : declaredFields) {
            if (declaredField.getAnnotation(Schema.class) != null) {
                Map<String, String> map = new HashMap<>();
                map.put("header", declaredField.getAnnotation(Schema.class).description());
                map.put("alias", declaredField.getName());
                list.add(map);
            }
        }
        return list;
    }
}
